﻿using Microsoft.AspNetCore.Mvc;
using PLCS.Application.Contracts.ConfigApp;
using PLCS.Application.Contracts.ConfigApp.Dtos;
using PLCS.Application.Contracts.EquipmentApp.Dtos;
using PLCS.Domain;
using PLCS.Domain.Configs;

using Volo.Abp.Application.Dtos;
using PLCS.Domain.Equipments;

using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;
using PLCS.Domain.Shared.Enums;

namespace PLCS.Application.ConfigApp;

public class ConfigAppService : CrudAppService<Config, ConfigDto, Guid, PagedResultRequestDto, ConfigEditDto>, IConfigAppService
{
    private readonly IRepository<Config, Guid> _repository;
    private readonly PLCSConfigurationService _pLCSConfigurationService;

    public ConfigAppService(IRepository<Config, Guid> repository, PLCSConfigurationService pLCSConfigurationService) : base(repository)
    {
        _repository = repository;
        _pLCSConfigurationService = pLCSConfigurationService;
    }

    public override async Task<ConfigDto> CreateAsync(ConfigEditDto input)
    {
        var entity = await MapToEntityAsync(input);
        await Repository.InsertAsync(entity, autoSave: true);
        _pLCSConfigurationService.UpdateConfiguration(entity);
        return await MapToGetOutputDtoAsync(entity);
    }

    public override async Task DeleteAsync(Guid id)
    {
        await DeleteByIdAsync(id);
        var entity = await _repository.FindAsync(id);
        _pLCSConfigurationService.DeleteConfiguration(entity);
    }

    public async Task<string> GetConfigByNameAsync(string name)
    {
        var res = await Task.Run(() => _pLCSConfigurationService.GetConfiguration(name));
        Check.NotNull(res, name, $"配置‘{name}’，不存在");
        return res;
    }

    public async Task<IEnumerable<ConfigDto>> GetConfigListAsync()
    {
        var entities = await Task.Run(() => _pLCSConfigurationService.GetConfigurations());
        return ObjectMapper.Map<IEnumerable<Config>, IEnumerable<ConfigDto>>(entities);
    }

    public async Task<PagedResultDto<ConfigDto>> GetListBySearchAsync(PagedResultRequestDto input, string? name)
    {
        await CheckGetListPolicyAsync();

        var query = await CreateFilteredQueryAsync(input);

        query = query.WhereIf(!string.IsNullOrEmpty(name), x => x.Name == name);
        var totalCount = await AsyncExecuter.CountAsync(query);
        query = ApplyPaging(query, input);

        var entities = await AsyncExecuter.ToListAsync(query);
        var entityDtos = await MapToGetListOutputDtosAsync(entities);

        return new PagedResultDto<ConfigDto>(
            totalCount,
            entityDtos
        );
    }

    public async Task UpdateAsync(ConfigEditDto config)
    {
        var entity = await GetEntityByIdAsync(config.Id);
        await MapToEntityAsync(config, entity);
        await Repository.UpdateAsync(entity, autoSave: true);

        _pLCSConfigurationService.UpdateConfiguration(entity);
    }
}